<template>
  <div class="dashboard-container">
    <h1 class="dashboard-title">套餐销售数据看板</h1>

    <!-- 时间筛选 -->
    <div class="time-filter">
      <el-select v-model="selectedYear" placeholder="选择年份" @change="fetchData">
        <el-option
          v-for="year in availableYears"
          :key="year"
          :label="`${year}年`"
          :value="year"
        />
      </el-select>
      
      <el-select v-model="selectedQuarter" placeholder="选择季度" @change="fetchData">
        <el-option
          v-for="q in quarters"
          :key="q.value"
          :label="q.label"
          :value="q.value"
        />
      </el-select>
    </div>

    <!-- 图表展示 -->
    <div class="charts-row">
      <!-- 左侧：套餐销量占比饼图 -->
      <div class="chart-section">
        <h2 class="chart-title">套餐销量占比</h2>
        <div class="chart-container">
          <div ref="pieChart" class="chart"></div>
        </div>
        <div class="chart-legend">
          <span
            class="legend-item"
            v-for="(item, index) in packageData"
            :key="index"
          >
            <span
              class="legend-color"
              :style="{ backgroundColor: colors[index] }"
            ></span>
            <span>{{ item.packageName }}</span>
          </span>
        </div>
      </div>

      <!-- 右侧：套餐收入柱状图 -->
      <div class="chart-section">
        <h2 class="chart-title">套餐收入统计</h2>
        <div class="chart-container">
          <div ref="barChartRight" class="chart"></div>
        </div>
      </div>
    </div>

    <!-- 底部：销量趋势折线图 -->
    <div class="chart-section full-width">
      <h2 class="chart-title">套餐销量趋势</h2>
      <div class="chart-container">
        <div ref="lineChart" class="chart"></div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import * as echarts from "echarts";
import axios from "axios";
import { ElMessage } from "element-plus";

// 加载状态
const loading = ref(false);

// 筛选条件
const selectedYear = ref(new Date().getFullYear());
const selectedQuarter = ref(Math.floor(new Date().getMonth() / 3) + 1);
const availableYears = ref(Array.from({length: 5}, (_, i) => new Date().getFullYear() - i));
const quarters = ref([
  { value: 1, label: '第一季度' },
  { value: 2, label: '第二季度' },
  { value: 3, label: '第三季度' },
  { value: 4, label: '第四季度' }
]);

// 图表数据
const packageData = ref([]);
const colors = [
  "#5470C6", "#91CC75", "#FAC858", "#EE6666", 
  "#73C0DE", "#3BA272", "#FC8452", "#9A60B4"
];

// 图表DOM引用
const pieChart = ref(null);
const barChartRight = ref(null);
const lineChart = ref(null); // 将原来的barChart改为lineChart

// 获取套餐季度销量数据
const fetchData = async () => {
  try {
    loading.value = true;
    
    const params = {
      year: selectedYear.value,
      quarter: selectedQuarter.value
    };
    
    const response = await axios.post('http://localhost:8081/meal-packages/list', params, {
        headers: {
        'Content-Type': 'application/json'
        }
    });
    
    if (response.data.code === 200) {
      packageData.value = response.data.data;
      updateCharts();
    } else {
      ElMessage.error(response.data.message || '获取套餐数据失败');
    }
  } catch (error) {
    ElMessage.error('请求失败: ' + error.message);
  } finally {
    loading.value = false;
  }
};

// 更新所有图表
const updateCharts = () => {
  updatePieChart();
  updateRightBarChart();
  updateLineChart(); // 改为更新折线图
};

// 更新销量占比饼图
const updatePieChart = () => {
  const chart = echarts.getInstanceByDom(pieChart.value) || echarts.init(pieChart.value);
  
  const data = packageData.value.map(item => ({
    name: item.packageName,
    value: item.totalSales
  }));
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c}份 ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center',
      data: data.map(item => item.name)
    },
    series: [
      {
        name: '销量占比',
        type: 'pie',
        radius: ['50%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: data.map((item, index) => ({
          ...item,
          itemStyle: {
            color: colors[index % colors.length]
          }
        }))
      }
    ]
  };
  
  chart.setOption(option);
};

// 更新右侧收入柱状图
const updateRightBarChart = () => {
  const chart = echarts.getInstanceByDom(barChartRight.value) || echarts.init(barChartRight.value);
  
  const xData = packageData.value.map(item => item.packageName);
  const revenueData = packageData.value.map(item => item.totalRevenue);
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: '{b}<br/>收入: ¥{c}'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: xData,
      axisLabel: {
        rotate: 30,
        interval: 0
      }
    },
    yAxis: {
      type: 'value',
      name: '收入(元)',
      axisLabel: {
        formatter: '¥{value}'
      }
    },
    series: [
      {
        name: '收入',
        type: 'bar',
        barWidth: '40%',
        data: revenueData,
        itemStyle: {
          color: function(params) {
            return colors[params.dataIndex % colors.length];
          },
          borderRadius: [4, 4, 0, 0]
        },
        label: {
          show: true,
          position: 'top',
          formatter: '¥{c}'
        }
      }
    ]
  };
  
  chart.setOption(option);
};

// 更新底部销量趋势折线图
const updateLineChart = () => {
  const chart = echarts.getInstanceByDom(lineChart.value) || echarts.init(lineChart.value);
  
  const xData = packageData.value.map(item => item.packageName);
  const salesData = packageData.value.map(item => item.totalSales);
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      },
      formatter: '{b}<br/>销量: {c}份'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: xData,
      axisLabel: {
        rotate: 30
      }
    },
    yAxis: {
      type: 'value',
      name: '销量(份)'
    },
    series: [
      {
        name: '销量趋势',
        type: 'line',
        smooth: true,
        lineStyle: {
          width: 3,
          color: '#5470C6'
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              color: 'rgba(84, 112, 198, 0.5)'
            },
            {
              offset: 1,
              color: 'rgba(84, 112, 198, 0.1)'
            }
          ])
        },
        emphasis: {
          focus: 'series'
        },
        data: salesData,
        markPoint: {
          data: [
            { type: 'max', name: '最大值' },
            { type: 'min', name: '最小值' }
          ]
        },
        markLine: {
          data: [{ type: 'average', name: '平均值' }]
        }
      }
    ]
  };
  
  chart.setOption(option);
};

onMounted(() => {
  fetchData();
  
  // 响应式调整图表大小
  window.addEventListener('resize', () => {
    pieChart.value && echarts.getInstanceByDom(pieChart.value)?.resize();
    barChartRight.value && echarts.getInstanceByDom(barChartRight.value)?.resize();
    lineChart.value && echarts.getInstanceByDom(lineChart.value)?.resize();
  });
});
</script>

<style scoped>
/* 样式保持不变 */
.dashboard-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.dashboard-title {
  font-size: 24px;
  color: #333;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.time-filter {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
}

.charts-row {
  display: flex;
  gap: 15px;
  margin-bottom: 15px;
}

.chart-section {
  flex: 1;
  background: #f9f9f9;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.full-width {
  width: 100%;
}

.chart-title {
  font-size: 18px;
  color: #333;
  margin-bottom: 15px;
  text-align: center;
}

.chart-container {
  width: 100%;
  height: 350px;
}

.chart {
  width: 100%;
  height: 100%;
}

.chart-legend {
  display: flex;
  justify-content: center;
  margin-top: 15px;
  flex-wrap: wrap;
  gap: 10px 20px;
}

.legend-item {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #666;
}

.legend-color {
  display: inline-block;
  width: 12px;
  height: 12px;
  border-radius: 2px;
  margin-right: 6px;
}

@media (max-width: 768px) {
  .charts-row {
    flex-direction: column;
  }
  
  .chart-container {
    height: 300px;
  }
}
</style>